package com.yuanqi.contoller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.entity.Inventory;
import com.yuanqi.entity.WareDelivery;
import com.yuanqi.entity.WareGrn;
import com.yuanqi.entity.WareStockCount;
import com.yuanqi.mapper.ProductMapper;
import com.yuanqi.mapper.SkuMapper;
import com.yuanqi.service.InventoryService;
import com.yuanqi.service.WareDeliveryService;
import com.yuanqi.service.WareGrnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仓库管理控制器
 */
@RestController
@RequestMapping("/ware")
public class WareController {
    
    @Autowired
    private WareGrnService wareGrnService;
    
    @Autowired
    private WareDeliveryService wareDeliveryService;
    
    @Autowired
    private InventoryService inventoryService;
    
    @Autowired
    private SkuMapper skuMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private com.yuanqi.service.WareStockCountService wareStockCountService;
    
    /**
     * 查询仓库状况（库存）
     */
    @GetMapping("/inventory")
    public ResponseEntity<Map<String, Object>> inventory(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Long skuId
    ) {
        Page<Inventory> pageParam = new Page<>(page, size);
        // 调用库存服务查询库存情况
        IPage<Inventory> pageResult = inventoryService.page(pageParam);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 入库单列表
     */
    @GetMapping("/grn/list")
    public ResponseEntity<Map<String, Object>> grnList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String grnCode,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Integer status
    ) {
        try {
            IPage<WareGrn> pageResult = wareGrnService.listGrns(page, size, grnCode, warehouseId, status);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("message", "查询成功");
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("pages", pageResult.getPages());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "查询入库单列表失败: " + e.getMessage());
            errorResult.put("records", new ArrayList<>());
            errorResult.put("total", 0);
            errorResult.put("pages", 0);
            errorResult.put("current", page);
            errorResult.put("size", size);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }
    
    /**
     * SKU 简单列表（用于下拉）
     */
    @GetMapping("/sku/list")
    public ResponseEntity<Map<String, Object>> skuList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "100") Integer size,
            @RequestParam(required = false) String code
    ) {
        try {
            com.baomidou.mybatisplus.core.metadata.IPage<com.yuanqi.entity.Sku> pageResult =
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.yuanqi.entity.Sku>(page, size);
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.yuanqi.entity.Sku> qw = new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            if (org.springframework.util.StringUtils.hasText(code)) {
                qw.like(com.yuanqi.entity.Sku::getSkuCode, code);
            }
            pageResult = skuMapper.selectPage(pageResult, qw);
            // 富化：附带商品名称
            java.util.List<java.util.Map<String, Object>> enriched = new java.util.ArrayList<>();
            for (com.yuanqi.entity.Sku sku : pageResult.getRecords()) {
                java.util.Map<String, Object> row = new java.util.HashMap<>();
                row.put("id", sku.getId());
                row.put("skuCode", sku.getSkuCode());
                row.put("productId", sku.getProductId());
                try {
                    com.yuanqi.entity.Product p = productMapper.selectById(sku.getProductId());
                    if (p != null) {
                        row.put("productName", p.getProductName());
                    } else {
                        row.put("productName", "未知商品");
                    }
                } catch (Exception ignore) {
                    row.put("productName", "未知商品");
                }
                enriched.add(row);
            }
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("message", "查询成功");
            result.put("records", enriched);
            result.put("total", pageResult.getTotal());
            result.put("pages", pageResult.getPages());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "查询SKU列表失败: " + e.getMessage());
            errorResult.put("records", new ArrayList<>());
            errorResult.put("total", 0);
            errorResult.put("pages", 0);
            errorResult.put("current", page);
            errorResult.put("size", size);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }
    
    /**
     * 入库单详情
     */
    @GetMapping("/grn/{id}")
    public ResponseEntity<Map<String, Object>> grnDetail(@PathVariable Long id) {
        Map<String, Object> detail = wareGrnService.getGrnDetail(id);
        if (detail == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(detail);
    }
    
    /**
     * 创建入库单
     */
    @PostMapping("/grn")
    public ResponseEntity<Map<String, Object>> createGrn(@RequestBody Map<String, Object> requestData) {
        try {
            WareGrn grn = new WareGrn();
            
            // 设置入库单基本信息
            if (requestData.containsKey("grnCode")) {
                grn.setGrnCode(requestData.get("grnCode").toString());
            }
            
            if (requestData.containsKey("poId") && !requestData.get("poId").toString().isEmpty()) {
                grn.setPoId(Long.valueOf(requestData.get("poId").toString()));
            }
            
            if (requestData.containsKey("warehouseId")) {
                grn.setWarehouseId(Long.valueOf(requestData.get("warehouseId").toString()));
            }

            // 供应商 / 入库类型 / 入库日期 / 经办人
            if (requestData.containsKey("supplierId") && !requestData.get("supplierId").toString().isEmpty()) {
                grn.setSupplierId(Long.valueOf(requestData.get("supplierId").toString()));
            }
            if (requestData.containsKey("inboundType")) {
                grn.setInboundType(String.valueOf(requestData.get("inboundType")));
            }
            if (requestData.containsKey("inboundDate")) {
                try {
                    grn.setInboundDate(new java.util.Date(java.time.OffsetDateTime.parse(requestData.get("inboundDate").toString()).toInstant().toEpochMilli()));
                } catch (Exception e) {
                    grn.setInboundDate(new java.util.Date());
                }
            }
            if (requestData.containsKey("handler")) {
                grn.setHandler(String.valueOf(requestData.get("handler")));
            }
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> items = (List<Map<String, Object>>) requestData.get("items");
            
            if (items == null || items.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "入库单明细不能为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            boolean success = wareGrnService.createGrn(grn, items);
            if (success) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 0);
                response.put("message", "入库单创建成功");
                response.put("data", grn.getId());
                return ResponseEntity.status(HttpStatus.CREATED).body(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 500);
                errorResponse.put("message", "入库单创建失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "创建入库单时发生错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 更新入库单
     */
    @PutMapping("/grn/{id}")
    public ResponseEntity<Void> updateGrn(@PathVariable Long id, @RequestBody Map<String, Object> requestData) {
        WareGrn grn = new WareGrn();
        grn.setId(id);
        
        // 设置入库单基本信息
        if (requestData.containsKey("grnCode")) {
            grn.setGrnCode(requestData.get("grnCode").toString());
        }
        
        if (requestData.containsKey("poId")) {
            grn.setPoId(Long.valueOf(requestData.get("poId").toString()));
        }
        
        if (requestData.containsKey("warehouseId")) {
            grn.setWarehouseId(Long.valueOf(requestData.get("warehouseId").toString()));
        }
        
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> items = (List<Map<String, Object>>) requestData.get("items");
        
        boolean success = wareGrnService.updateGrn(grn, items);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 执行入库
     */
    @PostMapping("/grn/{id}/execute")
    public ResponseEntity<Void> executeGrn(@PathVariable Long id) {
        boolean success = wareGrnService.executeGrn(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 审核入库单
     */
    @PostMapping("/grn/{id}/approve")
    public ResponseEntity<Void> approveGrn(@PathVariable Long id) {
        boolean success = wareGrnService.approveGrn(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 驳回入库单
     */
    @PostMapping("/grn/{id}/reject")
    public ResponseEntity<Void> rejectGrn(@PathVariable Long id, @RequestBody(required = false) Map<String, Object> requestData) {
        boolean success = wareGrnService.rejectGrn(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 提交入库单审核
     */
    @PostMapping("/grn/{id}/submit")
    public ResponseEntity<Void> submitGrn(@PathVariable Long id) {
        boolean success = wareGrnService.submitGrn(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 入库记录查询
     */
    @GetMapping("/grn/records")
    public ResponseEntity<Map<String, Object>> grnRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String grnCode,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Long skuId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate
    ) {
        try {
            List<Map<String, Object>> allRecords = wareGrnService.getGrnRecords(grnCode, productName, warehouseId, skuId, startDate, endDate);
            
            // 手动分页
            int total = allRecords.size();
            int start = (page - 1) * size;
            int end = Math.min(start + size, total);
            List<Map<String, Object>> pageRecords = allRecords.subList(start, end);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("message", "查询成功");
            result.put("records", pageRecords);
            result.put("total", total);
            result.put("pages", (int) Math.ceil((double) total / size));
            result.put("current", page);
            result.put("size", size);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "查询入库记录失败: " + e.getMessage());
            errorResult.put("records", new ArrayList<>());
            errorResult.put("total", 0);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }
    
    /**
     * 出库记录查询
     */
    @GetMapping("/delivery/records")
    public ResponseEntity<Map<String, Object>> deliveryRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String deliveryCode,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Long skuId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate
    ) {
        try {
            List<Map<String, Object>> allRecords = wareDeliveryService.getDeliveryRecords(deliveryCode, productName, warehouseId, skuId, startDate, endDate);
            
            // 手动分页
            int total = allRecords.size();
            int start = (page - 1) * size;
            int end = Math.min(start + size, total);
            List<Map<String, Object>> pageRecords = allRecords.subList(start, end);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("message", "查询成功");
            result.put("records", pageRecords);
            result.put("total", total);
            result.put("pages", (int) Math.ceil((double) total / size));
            result.put("current", page);
            result.put("size", size);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "查询出库记录失败: " + e.getMessage());
            errorResult.put("records", new ArrayList<>());
            errorResult.put("total", 0);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }
    
    /**
     * 出库单列表
     */
    @GetMapping("/delivery/list")
    public ResponseEntity<Map<String, Object>> deliveryList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String deliveryCode,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Integer status
    ) {
        IPage<WareDelivery> pageResult = wareDeliveryService.listDeliveries(page, size, deliveryCode, warehouseId, status);
        
        Map<String, Object> result = new HashMap<>();
        result.put("records", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pages", pageResult.getPages());
        result.put("current", pageResult.getCurrent());
        result.put("size", pageResult.getSize());
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 出库单详情
     */
    @GetMapping("/delivery/{id}")
    public ResponseEntity<Map<String, Object>> deliveryDetail(@PathVariable Long id) {
        Map<String, Object> detail = wareDeliveryService.getDeliveryDetail(id);
        if (detail == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(detail);
    }
    
    /**
     * 创建出库单
     */
    @PostMapping("/delivery")
    public ResponseEntity<Void> createDelivery(@RequestBody Map<String, Object> requestData) {
        WareDelivery delivery = new WareDelivery();
        
        // 设置出库单基本信息
        if (requestData.containsKey("deliveryCode")) {
            delivery.setDeliveryCode(requestData.get("deliveryCode").toString());
        }
        
        if (requestData.containsKey("soId")) {
            delivery.setSoId(Long.valueOf(requestData.get("soId").toString()));
        }
        
        if (requestData.containsKey("warehouseId")) {
            delivery.setWarehouseId(Long.valueOf(requestData.get("warehouseId").toString()));
        }
        
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> items = (List<Map<String, Object>>) requestData.get("items");
        
        boolean success = wareDeliveryService.createDelivery(delivery, items);
        if (success) {
            return new ResponseEntity<>(HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    /**
     * 更新出库单
     */
    @PutMapping("/delivery/{id}")
    public ResponseEntity<Void> updateDelivery(@PathVariable Long id, @RequestBody Map<String, Object> requestData) {
        WareDelivery delivery = new WareDelivery();
        delivery.setId(id);
        
        // 设置出库单基本信息
        if (requestData.containsKey("deliveryCode")) {
            delivery.setDeliveryCode(requestData.get("deliveryCode").toString());
        }
        
        if (requestData.containsKey("soId")) {
            delivery.setSoId(Long.valueOf(requestData.get("soId").toString()));
        }
        
        if (requestData.containsKey("warehouseId")) {
            delivery.setWarehouseId(Long.valueOf(requestData.get("warehouseId").toString()));
        }
        
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> items = (List<Map<String, Object>>) requestData.get("items");
        
        boolean success = wareDeliveryService.updateDelivery(delivery, items);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 执行出库
     */
    @PostMapping("/delivery/{id}/execute")
    public ResponseEntity<Map<String, Object>> executeDelivery(@PathVariable Long id) {
        try {
            boolean success = wareDeliveryService.executeDelivery(id);
            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 0);
                result.put("message", "出库操作成功");
                return ResponseEntity.ok(result);
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 400);
                result.put("message", "出库操作失败");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
            }
        } catch (RuntimeException e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 400);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "出库操作失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
    
    /**
     * 提交出库单审核
     */
    @PostMapping("/delivery/{id}/submit")
    public ResponseEntity<Void> submitDelivery(@PathVariable Long id) {
        boolean success = wareDeliveryService.submitDelivery(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 审核出库单
     */
    @PostMapping("/delivery/{id}/approve")
    public ResponseEntity<Void> approveDelivery(@PathVariable Long id) {
        boolean success = wareDeliveryService.approveDelivery(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 驳回出库单
     */
    @PostMapping("/delivery/{id}/reject")
    public ResponseEntity<Void> rejectDelivery(@PathVariable Long id, @RequestBody(required = false) Map<String, Object> requestData) {
        boolean success = wareDeliveryService.rejectDelivery(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 删除出库单
     */
    @DeleteMapping("/delivery/{id}")
    public ResponseEntity<Void> deleteDelivery(@PathVariable Long id) {
        boolean success = wareDeliveryService.removeById(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 库存盘点单列表
     */
    @GetMapping("/stock-count/list")
    public ResponseEntity<Map<String, Object>> stockCountList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String countCode,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Integer status
    ) {
        try {
            IPage<WareStockCount> pageResult = wareStockCountService.listStockCounts(page, size, countCode, warehouseId, status);
            
            Map<String, Object> result = new HashMap<>();
            result.put("code", 0);
            result.put("message", "查询成功");
            result.put("records", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("pages", pageResult.getPages());
            result.put("current", pageResult.getCurrent());
            result.put("size", pageResult.getSize());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "查询盘点单列表失败: " + e.getMessage());
            errorResult.put("records", new ArrayList<>());
            errorResult.put("total", 0);
            
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
        }
    }
    
    /**
     * 盘点单详情
     */
    @GetMapping("/stock-count/{id}")
    public ResponseEntity<Map<String, Object>> stockCountDetail(@PathVariable Long id) {
        Map<String, Object> detail = wareStockCountService.getStockCountDetail(id);
        if (detail == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(detail);
    }
    
    /**
     * 创建盘点单
     */
    @PostMapping("/stock-count")
    public ResponseEntity<Map<String, Object>> createStockCount(@RequestBody Map<String, Object> requestData) {
        try {
            WareStockCount stockCount = new WareStockCount();
            
            if (requestData.containsKey("countCode")) {
                stockCount.setCountCode(requestData.get("countCode").toString());
            }
            
            if (requestData.containsKey("warehouseId")) {
                stockCount.setWarehouseId(Long.valueOf(requestData.get("warehouseId").toString()));
            }
            
            if (requestData.containsKey("createdBy")) {
                stockCount.setCreatedBy(requestData.get("createdBy").toString());
            }
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> items = (List<Map<String, Object>>) requestData.get("items");
            
            if (items == null || items.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "盘点明细不能为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            boolean success = wareStockCountService.createStockCount(stockCount, items);
            if (success) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 0);
                response.put("message", "盘点单创建成功");
                response.put("data", stockCount.getId());
                return ResponseEntity.status(HttpStatus.CREATED).body(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 500);
                errorResponse.put("message", "盘点单创建失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "创建盘点单时发生错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 生成盘点任务
     */
    @PostMapping("/stock-count/generate")
    public ResponseEntity<Map<String, Object>> generateStockCountTask(@RequestBody Map<String, Object> requestData) {
        try {
            Long warehouseId = Long.valueOf(requestData.get("warehouseId").toString());
            Long stockCountId = wareStockCountService.generateStockCountTask(warehouseId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 0);
            response.put("message", "盘点任务生成成功");
            response.put("data", stockCountId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "生成盘点任务失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 提交盘点单审核
     */
    @PostMapping("/stock-count/{id}/submit")
    public ResponseEntity<Void> submitStockCount(@PathVariable Long id) {
        boolean success = wareStockCountService.submitStockCount(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 审核盘点单
     */
    @PostMapping("/stock-count/{id}/approve")
    public ResponseEntity<Void> approveStockCount(@PathVariable Long id) {
        boolean success = wareStockCountService.approveStockCount(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 驳回盘点单
     */
    @PostMapping("/stock-count/{id}/reject")
    public ResponseEntity<Void> rejectStockCount(@PathVariable Long id, @RequestBody(required = false) Map<String, Object> requestData) {
        boolean success = wareStockCountService.rejectStockCount(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 更新盘点单
     */
    @PutMapping("/stock-count/{id}")
    public ResponseEntity<Void> updateStockCount(@PathVariable Long id, @RequestBody Map<String, Object> requestData) {
        WareStockCount stockCount = new WareStockCount();
        stockCount.setId(id);
        
        // 设置盘点单基本信息
        if (requestData.containsKey("countCode")) {
            stockCount.setCountCode(requestData.get("countCode").toString());
        }
        
        if (requestData.containsKey("warehouseId")) {
            stockCount.setWarehouseId(Long.valueOf(requestData.get("warehouseId").toString()));
        }
        
        if (requestData.containsKey("createdBy")) {
            stockCount.setCreatedBy(requestData.get("createdBy").toString());
        }
        
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> items = (List<Map<String, Object>>) requestData.get("items");
        
        boolean success = wareStockCountService.updateStockCount(stockCount, items);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 执行盘点调整
     */
    @PostMapping("/stock-count/{id}/execute")
    public ResponseEntity<Void> executeStockCount(@PathVariable Long id) {
        boolean success = wareStockCountService.executeStockCount(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
    
    /**
     * 删除盘点单
     */
    @DeleteMapping("/stock-count/{id}")
    public ResponseEntity<Void> deleteStockCount(@PathVariable Long id) {
        boolean success = wareStockCountService.removeById(id);
        if (success) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }
} 